package com.stone.serverless.beetl;

import com.stone.serverless.beetl.builder.SeMapperConfigBuilder;
import com.stone.serverless.beetl.loader.SeClassLoaderKit;
import com.stone.serverless.beetl.service.MapperRegisterServiceImpl;
import com.stone.serverless.sdk.event.ComponentRefresh;
import org.beetl.sql.core.DefaultConnectionSource;
import org.beetl.sql.core.MapperBuilder;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.mapper.DefaultMapperBuilder;

/**
 * @Description: TODO
 * @Author: MECHREVO
 * @Date: 2022/1/17 15:52
 * @Version: 1.0.0
 */
public class DbOutServiceRefreshManager implements ComponentRefresh {


    @Override
    public void refresh() {
        //SQLManager sqlManager = SessionSQLManager.getSQLManger(SqlTest.class);
        DefaultConnectionSource defaultConnectionSource = new DefaultConnectionSource();
        defaultConnectionSource.setMasterSource(NeedOutServiceManager.INSTANCE.dataSourceService.dataSource());

        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();

        Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
        SQLManager sqlManager = SQLManager.newBuilder(defaultConnectionSource).build();
        sqlManager.setClassLoaderKit(new SeClassLoaderKit(this.getClass().getClassLoader()));
        MapperBuilder mapperBuilder = sqlManager.getMapperBuilder();
        if(mapperBuilder instanceof DefaultMapperBuilder){
            ((DefaultMapperBuilder) mapperBuilder).setMapperConfig(new SeMapperConfigBuilder());
        }
        Thread.currentThread().setContextClassLoader(contextClassLoader);
        MapperRegisterServiceImpl.sqlManager = sqlManager;
    }
}
